package com.domor.service.system;

import com.domor.model.Menu;
import com.domor.model.User;
import com.domor.dao.system.SystemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SystemService {

    @Autowired
    private SystemDao dao;

    public User getUserByName(String username) {
        return dao.getUserByName(username);
    }

    public List<String> getUserButtons(int role){
        return dao.getButtonsByRole(role);
    }

    public List<Menu> getUserMenus(int role){
        return getMenuTree(dao.getMenusByRole(role));
    }

    private List<Menu> getMenuTree(List<Menu> menus) {
        List<Menu> resultMenus = new ArrayList<>();
        for(Menu menu : menus) {
            if(menu.getParentId() == 0) {
                menu.setChildren(getChildrenMenus(menu.getId(), menus));
                resultMenus.add(menu);
            }
        }
        return resultMenus;
    }

    private List<Menu> getChildrenMenus(int parentId, List<Menu> menus) {
        List<Menu> resultMenus = new ArrayList<>();
        for(Menu menu : menus) {
            int pid = menu.getParentId();
            if(pid == 0) continue;
            if(pid!=0 && parentId==pid) {
                menu.setChildren(getChildrenMenus(menu.getId(), menus));
                resultMenus.add(menu);
            }
        }
        return resultMenus;
    }

}
